import {appInitializer} from "../../AppInitializer";
import {BroadcastEvent} from "../../events/BroadcastEvent";
import SessionListData from "../../model/item/SessionListData";
import {SimpleDateFormat} from "../../utils/SimpleDateFormat"

var sdk = require('../../utils/echatim-sdk.js');
var WxNotificationCenter = require('../../utils/WxNotificationCenter.js')
let app = getApp();
let globalStore = app.globalData.globalStore;


Page({
  data: {
    items:[]
  },
  onLoad:function(){
    const self = this;
    const app = getApp();
    console.log(app.globalData);
    if(!app.globalData.im){
      wx.navigateTo({
        url: '../login/login',
        events: {
          onLogin:(data)=>{
            console.log('receive onLogin event:'+JSON.stringify(data));
            const auid = data.auid;
            const token = data.token;
            self.onLogin(auid, token);
          }
        }
      })
    }
    WxNotificationCenter.addNotification(BroadcastEvent.EVENT_SDK_INIT, this.onSDKInit, this);
    // 绑定实时刷新回调
    globalStore.addSessionListener(this.onSessionUpdate.bind(this));
    // 使用初始化的数据更新列表
    this.onSessionUpdate(globalStore.sessionList);
  },

  // sessions:Array<HistorySessionDTO>
  onSessionUpdate(sessions){
    const items = sessions.map((v)=>{
      const data =  new SessionListData();
      data.id = v.toTarget + '';
      data.avatar = v.toTargetAvatar;
      data.name = v.toTargetName;
      data.body = v.body.body;
      data.unread = v.unread;
      data.createTime = v.createTime;
      data.createTimeStr = SimpleDateFormat.formatDateStr(v.createTime, 'MM-dd hh:mm');

      return data;
    });

    console.log(items);

    this.setData({
      items : items
    });
  },

  onSDKInit:function(im){
     wx.showToast({title: 'SDK初始化成功.'});
  },

  onLogin:(auid, token)=>{
    const app = getApp();
    app.globalData.im = sdk.im;
    appInitializer.init(app, auid, token);
  }
})
